<template>
  <div id="choose">
    <el-row class="bgColor">
      <el-col :xs="24" :sm="24" :lg="24" class="choose-flex">
        <el-radio-group v-model="choose" class="group-radio" :class="{'groupCompany': isCompany}">
          <el-radio :label="1" class="flex-radio radioEl">集团</el-radio>
          <el-radio :label="2" class="flex-radio" :class="{'radioCompany': isCompany}">
            事业群
            <el-select 
              :disabled="choose !== 2" 
              style="margin-left: 6px;" 
              v-model="selectedGroup" 
              placeholder="请选择事业群" 
              clearable 
              filterable
            >
              <el-option 
                v-for="item in group_selector" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-radio>
        </el-radio-group>
        <div class="time-box">
          <label class="col-form-label" style="font-size:15px;font-weight: 500;">时间段：</label>
          <el-date-picker
              v-if="!isShowKpiData"
              v-model="dateTimes"
              :type="dateType"
              align="right"
              size="small"
              :value-format="dateType =='daterange' ? 'yyyy-MM-dd' : 'yyyy-MM'"
              :unlink-panels="true"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @focus="focus"
              @blur="blur"
              :picker-options="pickerOptions" 
              :default-time="dateTimes"                        
              class="mr-4">
          </el-date-picker>

          <el-date-picker
            v-else
            v-model="monthKpi"
            type="month"
            value-format="yyyy-MM"
            placeholder="请选择月份">
          </el-date-picker>
        </div>
      </el-col>
    </el-row>

    <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { removeToken, removeName } from '@/utils/auth'
import { getHeader } from '@/app.config'
import companyVue from '../report/qualityKpi/company.vue'

export default {
  props: {
    dateType: {
      type: String,
      default: 'daterange'
    },
    isShowKpiData: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      choose: 1,
      isCompany: true,
      selectedGroup: '',
      groupId: '',
      group_selector: [],
      dateTimes: [],
      monthKpi: '',
      pickerOptions: {
          shortcuts: [{
              text: '最近一周',
              onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
              }
          }, {
              text: '最近一个月',
              onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
              }
          }, {
              text: '最近三个月',
              onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
              }
          },
          {
              text: '今年',
              onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
              const start = new Date(new Date().getFullYear(), 0);
              start.setTime(start.getTime());
              picker.$emit('pick', [start, end]);
              }
          },
          {
              text: '去年',
              onClick(picker) {
              const end = new Date(new Date().getFullYear() - 1, 11, 31);
              const start = new Date(new Date().getFullYear() - 1, 0);
              start.setTime(start.getTime());
              picker.$emit('pick', [start, end]);
              }
          }]
      }
    }
  },
  computed: {
    ...mapState({
      chooseList: state => state.chooseList
    })
  },
  watch: {
    isCompany(bool) {
      if(!bool) this.choose = 2      
    },
    choose(val) {
      if(val === 2) {
        if(this.chooseList.groupId == '') {
          this.groupId = this.group_selector[0].value
          this.selectedGroup = this.group_selector[0].label
        }
        this.search()
      } else {
        this.groupId = ''
        this.search()
      }
    },
    monthKpi(newDate) {
      this.search() 
    },
    selectedGroup(val) {
      //if(this.choose == 2) { 
        this.group_selector.forEach(value => {
          if(value.value == val) {
            this.groupId = value.value
            this.selectedGroup = value.label
          }
        })  
        this.search()           
      //}
    }
  },
  created() {
    this.defaultTime()
    this.init()
  },
  // mounted() {
  //   this.$nextTick(() => {
  //     //this.defaultTime()
  //   })
  // },
  methods: {
    ...mapMutations([
      'setChoose'
    ]),
    formatDateTime(date) {  
            let y = date.getFullYear();  
            let m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;  
            let d = date.getDate();  
            d = d < 10 ? ('0' + d) : d;  
            let h = date.getHours();  
            h=h < 10 ? ('0' + h) : h;  
            let minute = date.getMinutes();  
            minute = minute < 10 ? ('0' + minute) : minute;  
            let second=date.getSeconds();  
            second=second < 10 ? ('0' + second) : second;  
            return y + '-' + m + '-' + d   //+' '+h+':'+minute+':'+second;  
        },
    defaultTime() {
      if(!this.chooseList.dateTimes.length) {
        // let end = new Date()
        // let start = new Date()
        
        // let ys = start.getFullYear()
        // let ms = start.getMonth() 

        // if(ms == 0) { 
        //   ms = 12 
        // }
        
        // let ye = start.getFullYear()
        // let me = start.getMonth() + 1

        // if(ms.toString().length == 1) {
        //   ms = "0" + ms
        // }
        // if(me.toString().length == 1) {
        //   me = "0" + me
        // }
        // let starting = `${ys}-${ms}`
        // let ending = `${ye}-${me}`
       
        // this.dateTimes = [starting, ending]
            let end = new Date();
            let start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); // 近一个月的时间
            start = this.formatDateTime(start) //格式化日期
            end = this.formatDateTime(end)
            this.dateTimes = [start, end] 
            console.log(8,this.dateTimes)
      } else {
        this.dateTimes = this.chooseList.dateTimes
        console.log( 'elsethis.dateTimes',this.dateTimes )
      }

      if(this.chooseList.monthKpi) {
        this.monthKpi = this.chooseList.monthKpi.split(',')[1]
      } else {
        let now = new Date()
        let yn = now.getFullYear()
        let mn = now.getMonth() + 1
        if(mn.toString().length == 1) {
          mn = "0" + mn
        }
        let nowTime = `${yn}-${mn}`
        this.monthKpi = nowTime
      }
      // this.search()
    },
    focus() {
      let end = new Date()
      let start = new Date()

      let ys = start.getFullYear()
      let ms = start.getMonth()

      let ye = start.getFullYear()
      let me = start.getMonth() + 1
      if(ms.toString().length == 1) {
        ms = "0" + ms
      }
      if(me.toString().length == 1) {
        me = "0" + me
      }
      let starting = `${ys}-${ms}`
      let ending = `${ye}-${me}`
      if(this.chooseList.dateTimes[0] == starting && this.chooseList.dateTimes[1] == ending) {
        this.dateTimes = []
      } else {
        this.dateTimes = []
      }
    },
    blur() {
      let end = new Date()
      let start = new Date()

      let ys = start.getFullYear()
      let ms = start.getMonth()

      let ye = start.getFullYear()
      let me = start.getMonth() + 1
      if(ms.toString().length == 1) {
        ms = "0" + ms
      }
      if(me.toString().length == 1) {
        me = "0" + me
      }
      let starting = `${ys}-${ms}`
      let ending = `${ye}-${me}`
      if(!this.chooseList.dateTimes.length) {
        this.dateTimes = [starting, ending]
      }
      this.search()
    },
    init() {
      this.$axios.get('/api/account/personal_group_dept', {headers: getHeader()})
      .then((res) => {
        if(res.data.code === 200) {
          this.group_selector = res.data.group_info
          if(!this.chooseList.groupValue) {
            this.selectedGroup = this.group_selector[0].label
            this.groupId = this.group_selector[0].value
          } else {
            this.selectedGroup = this.chooseList.groupValue
            this.groupId = this.chooseList.groupId
          }
          this.isCompany = res.data.view_company
          if(this.$route.path == '/documentation/datas') {
            this.isCompany = false
          }
          if(this.$route.path.indexOf('documentation') > 0) {
            this.isCompany = false
          }
        } else if (res.data.code == 401) {
          removeToken()
          removeName()
          this.$message.error('登陆超时或该账号已被登出，请您重新登录');
          this.$router.push({
              path: '/#/login'
          })
        } 
      })
    },
    search() {
      let time, dateTimes, groupId, groupValue, radio, monthKpi
      this.dateTimes ? time = this.dateTimes.join(',') : time = ''  
      dateTimes = this.dateTimes
      groupId = this.groupId
      groupValue = this.selectedGroup
      radio = this.choose
      if(this.monthKpi) {
        let current = this.monthKpi.split('-')[0]
        monthKpi = `${current}-01,${this.monthKpi}`
      } else {
        monthKpi = ''
      }

      this.setChoose({
        time,
        dateTimes,
        groupId,
        groupValue,
        radio,
        monthKpi
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  #choose{
    .bgColor{
      background: #ffffff;
      padding: 20px;
      .choose-flex{
        display: flex;
        .group-radio{
          flex: 0 0 25%;
          margin: auto;
          display: flex;
          flex-wrap: wrap;
          .flex-radio{
            flex: 1;
            margin: auto;
          }
          .radioCompany{
            margin: auto 18px;
          }
          .radioEl{
            flex: 0 0 8%;
          }
        }
        .groupCompany{
          flex: 0 0 30%;
        }
        .time-box{
          flex: 1;
          margin: auto;
          margin-left: 50px;
        }
      }
    }  
  }
  .mr-1, .mx-1 {
        margin-right: 1.58rem;
        margin-left: 2.1rem;
        /* padding-left: 2rem; */
    }
    .ml-3, .mx-3 {
        margin-left: 1rem!important;
    }
    .mr-4{
        width: 40%;
    }
    .ml-2{
        float: right;
        margin-right: 4%;
    }
    .col-form-label {
        padding-top: calc(.375rem + 1px);
        padding-bottom: calc(.375rem + 1px);
        margin-bottom: 0;
        font-size: inherit;
        line-height: 1.5;
        font-size: 15px;
    }
</style>